//
//  MyActionSheet.m
//  yuikemall
//
//  Created by yuike5 yuike5 on 12-6-2.
//  Copyright (c) 2012年 yuike. All rights reserved.
//

#import "MyActionSheet.h"
#import "CALayer+Additions.h"
#import "UIView+RectSize.h"
#import "UIViewAdditions.h"
#import "header.h"


@implementation MyActionSheet

-(NSInteger) numberOfButtons {
    return buttonTitles.count;// NSInteger
}



-(void) dealloc {
    YRelease(buttonTitles)
    YRelease(background)
    
    [super dealloc];
}

- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex {
    if (buttonTitles) {
        if (buttonTitles.count>0 && buttonIndex>=0 && buttonIndex<buttonTitles.count)
            return [buttonTitles objectAtIndex:buttonIndex];
    }
    return nil;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        //assert(false);
    }
    return self;
}

- (NSInteger)addButtonWithTitle:(NSString *)title {    // returns index of button. 0 based.
    
    // 空的不要。。。
    if (!title || title.length<=0) return -1;
    
    [buttonTitles addObject:title];
    return buttonTitles.count-1;
}

- (id)initWithDelegate:(id<MyActionSheetDelegate>)delegatex buttonTitles:(NSString *)buttonTitlesx, ... {
    self = [super init];
    if (self) {
        delegate = delegatex;
        
        buttonTitles=[[NSMutableArray alloc] init];
        
        va_list args;
        va_start(args, buttonTitlesx);
        for (NSString *arg = buttonTitlesx; arg != nil; arg = va_arg(args, NSString*))
            [buttonTitles addObject:arg];        
        va_end(args);
    }
    return self;
}

+(void) deepIntxFrame:(UIView*)view {
    for (UIView* sub in view.subviews)
        [self deepIntxFrame:sub];
    [view selfIntxFrame];
}

- (void)showFromRect:(CGRect)rectx inView:(UIView *)parentx animated:(BOOL)animated {
    
    self.frame = parentx.bounds;
    self.backgroundColor = [UIColor clearColor];
    // remove all subs...
    for (UIView* view in self.subviews)
        [view removeFromSuperview];
    rect = rectx;
    parent = parentx;
    
    // 计算 框框大概多大 item_bg
    if (background == nil) {
        UIImage* image = [UIImage imageNamed:@"myactionsheet_background.png"];
        image = [image stretchableImageWithLeftCapWidth:(image.size.width/2-1) topCapHeight:(image.size.height/2-1)];
        background = [[UIImageView alloc] initWithImage:image];
    }
    UIImage* pointer_up = [UIImage imageNamed:@"myactionsheet_pointer_up.png"];
    UIImage* pointer_right = [UIImage imageNamed:@"myactionsheet_pointer_right.png"];
    UIImage* item_bg = [UIImage imageNamed:@"myactionsheet_item_background.png"];
    CGSize sizetmp = item_bg.size;
    item_bg = [item_bg stretchableImageWithLeftCapWidth:sizetmp.width/3 topCapHeight:sizetmp.height/3];
    

    const int HEIGHT_HEAD = 6;
    const int HEIGHT_FOOT = 6;
    const int HEIGHT_ITEM = sizetmp.height;
    const int HEIGHT_GAP  = 6;
    
    // 测量字符串宽度。。。
    UIFont* font = [[UIButton buttonWithType:UIButtonTypeCustom] titleLabel].font;
    int maxWidth = 0;
    for (NSString* title in buttonTitles) {
        int width = [title sizeWithFont:font].width + 20;
        maxWidth = MAX(maxWidth, width);
    }    
    
    const int WIDTH_ITEM = MAX(sizetmp.width + 20, maxWidth);
    const int WIDTH_ITEM_LR = 6;
    
    
        
    int count = [self numberOfButtons];
    int main_height = 0;
    if (count <= 0) {
        main_height = HEIGHT_HEAD + HEIGHT_FOOT;
    } else {
        main_height = HEIGHT_HEAD + HEIGHT_FOOT + HEIGHT_ITEM*count + HEIGHT_GAP*(count-1);
    }
    
    int main_width = WIDTH_ITEM+WIDTH_ITEM_LR*2;
    // 横屏幕 首选 左边
    // 竖屏幕 首选 下面
    BOOL isLand = parentx.bounds.size.width > parentx.bounds.size.height;
    BOOL inLeft = false;//isLand; 首选下方
    
    if (isLand) {
        
        // 如果是横屏幕，如果左边 搁不下
        if (main_width+pointer_right.size.width > rect.origin.x) {
            inLeft = false;
        }
        
    } else { // is poart
        
        // 如果是竖屏幕，如果下面 搁不下
        if (main_height+pointer_up.size.height > parentx.bounds.size.height-rect.origin.y-rect.size.height)
            inLeft=true;
    }
    
    
    // pointer 排版
    UIImageView* pointer = nil;
    CGRect pointer_rect = CGRectZero;
    
    if (inLeft) {
        
        pointer = [[[UIImageView alloc] initWithImage:pointer_right] autorelease];
        pointer_rect.size = pointer_right.size;
        pointer_rect.origin.x = rect.origin.x - pointer_right.size.width;
        pointer_rect.origin.y = rect.origin.y+rect.size.height/2 - pointer_right.size.height/2;
        
    } else {
        
        pointer = [[[UIImageView alloc] initWithImage:pointer_up] autorelease];
        pointer_rect.size = pointer_up.size;
        pointer_rect.origin.y = rect.origin.y + rect.size.height;
        pointer_rect.origin.x = rect.origin.x+rect.size.width/2 - pointer_up.size.width/2;
        
    }
    pointer.frame = pointer_rect;
    [self addSubview:pointer];
    
    // main 排版
    CGRect main_rect = CGRectZero;
    main_rect.size.width = main_width;
    main_rect.size.height = main_height;
#define GLOBAL_BORDER 5
    if (inLeft) { // 在左边        
        main_rect.origin.x = pointer_rect.origin.x - main_width;
        main_rect.origin.y = pointer_rect.origin.y+pointer_rect.size.height/2 - main_height/2;
        // main 排版 -- 边界 检查。。。    
        CGRect parentBounds = parent.bounds;
        if (main_rect.origin.y < GLOBAL_BORDER) 
            main_rect.origin.y = GLOBAL_BORDER;
        if (main_rect.origin.y + main_rect.size.height>=parentBounds.size.height-GLOBAL_BORDER) 
            main_rect.origin.y = parentBounds.size.height-main_rect.size.height-1-GLOBAL_BORDER;   
    } else { // 在下面
        main_rect.origin.x = pointer_rect.origin.x+pointer_rect.size.width/2 - main_width/2;
        main_rect.origin.y = pointer_rect.origin.y+pointer_rect.size.height;
        // main 排版 -- 边界 检查。。。    
        CGRect parentBounds = parent.bounds;
        if (main_rect.origin.x < GLOBAL_BORDER) 
            main_rect.origin.x = GLOBAL_BORDER;
        if (main_rect.origin.x + main_rect.size.width>=parentBounds.size.width-GLOBAL_BORDER)
            main_rect.origin.x = parentBounds.size.width-main_rect.size.width-1-GLOBAL_BORDER;
    }     
    background.frame = main_rect;
    [self addSubview:background];
    
    // 布置按钮上去
    CGRect itembutton_rect = main_rect;
    itembutton_rect.origin.x += WIDTH_ITEM_LR;
    itembutton_rect.size.width -= WIDTH_ITEM_LR*2;
    itembutton_rect.origin.y += HEIGHT_HEAD;
    itembutton_rect.size.height = HEIGHT_ITEM;
    for (NSString* str in buttonTitles) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:str forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:item_bg forState:UIControlStateNormal];
        
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = [buttonTitles indexOfObject:str];
        
        button.frame = itembutton_rect;
        [self addSubview:button];        
        itembutton_rect.origin.y += HEIGHT_ITEM + HEIGHT_GAP;
    }
    
    [MyActionSheet deepIntxFrame: self]; // 文字不清晰的问题
    [parentx addSubview:self];
    if (animated) {
        CATransition *animationOut = [CATransition animation];
        animationOut.duration = 0.18f;        
        animationOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];	
        animationOut.type = kCATransitionFade;      
        [[parentx layer] addAnimation:animationOut forKey:nil];
    }
    
    UITapGestureRecognizer* tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
    tap.delegate = self;
    [self addGestureRecognizer: tap];
    
    UISwipeGestureRecognizer* swipe = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
    swipe.delegate = self;
    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer: swipe];
    
    swipe = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
    swipe.delegate = self;
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer: swipe];
    
    swipe = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
    swipe.delegate = self;
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer: swipe];
    
    swipe = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
    swipe.delegate = self;
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    [self addGestureRecognizer: swipe];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) 
												 name:UIDeviceOrientationDidChangeNotification object:nil];
    orientation = [UIApplication sharedApplication].statusBarOrientation;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    //CGPoint point = [touch locationInView: gestureRecognizer.view];
    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    //CGPoint point = [gestureRecognizer locationInView: gestureRecognizer.view];
    return TRUE;
}
//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//    UIView* view = [super hitTest:point withEvent:event];
//    if ([view isKindOfClass:[UIButton class]]) {
//        [self performSelector:@selector(handleGesture:) withObject:nil afterDelay:0.1f];
//    }
//    return view;
//}

- (void)deviceOrientationDidChange:(NSNotification *)notification { 
	if (!self.superview) {
		return;
	}
    UIInterfaceOrientation orientation2 = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation == orientation2) {
        return;
    }
	[self performSelector:@selector(handleGesture:) withObject:nil afterDelay:0.1f];
}

-(void)handleGesture:(UIGestureRecognizer*)gestureRecognizer {
    if ([delegate respondsToSelector:@selector(myActionSheetCancel:)])
        [delegate myActionSheetCancel:self];
    
    [self removeFromSuperview];
    if (true) {
        CATransition *animationOut = [CATransition animation];
        animationOut.duration = 0.18f;        
        animationOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];	
        animationOut.type = kCATransitionFade;      
        [[parent layer] addAnimation:animationOut forKey:nil];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) buttonPressed:(id)sender {
    
    int index = ((UIButton*)sender).tag;
    NSString* title = [self buttonTitleAtIndex:index];
    if ([delegate respondsToSelector:@selector(myActionSheet:clickedButtonAtIndex:title:)])
        [delegate myActionSheet:self clickedButtonAtIndex:index title:title];
    
    [self removeFromSuperview];
    if (true) {
        CATransition *animationOut = [CATransition animation];
        animationOut.duration = 0.18f;        
        animationOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];	
        animationOut.type = kCATransitionFade;      
        [[parent layer] addAnimation:animationOut forKey:nil];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
